class OrderBeautiesController < ApplicationController
  before_action :set_menu
  autocomplete :car_mo, :name, :full => true

  def index
  	@submenu = :order_beauty
    @title = '美容工单'
    @tasks_grid = initialize_grid(OrderBeauty, per_page: 8, order: 'id', order_direction: 'desc')
  end

  def new
  	@title = '美容工单/新增'
    @buttons.push :action => order_beauties_path, :label => "返回"
    @insurers = Insurer.all
    if params.has_key? :car_mo_check
      @car_brand = CarBrand.find params[:customer][:car_brand_id]
      @car_model = CarModel.find params[:customer][:car_model_id]
    end
  	if params.has_key? :check 
      @car_num = params[:n1]+params[:n2]+params[:n3]
      @customer = Customer.find_by_car_num @car_num
      if @customer.nil?
        @infos.push "没有客户记录"
      end
    end
    if params.has_key? :save
      @customer = Customer.find_by_car_num params[:car_num]
      if @customer.nil?
        @customer = Customer.create(customer_level_id: 1, name: params[:name], phone: params[:phone], car_num: params[:car_num], car_mo: params[:car_mo], car_fnum: params[:car_fnum], last_cf_mileage: params[:last_cf_mileage], oil_meter: params[:oil_meter], next_care_mileage: params[:next_care_mileage], next_care_date: params[:next_care_date], car_enum: params[:car_enum], insurer_id: params[:insurer], force_expire: params[:force_expire])  
        @order_beauty = OrderBeauty.create(customer_id: @customer.id, note: params[:note], user_id: current_user.id, important_note: params[:important_note])
        redirect_to order_beauty_path(:id=>@order_beauty.id)
      else
        @customer.update(last_cf_mileage: params[:last_cf_mileage], oil_meter: params[:oil_meter], next_care_mileage: params[:next_care_mileage], next_care_date: params[:next_care_date])
        @order_beauty = OrderBeauty.create(customer_id: @customer.id, note: params[:note], user_id: current_user.id, important_note: params[:important_note])
        redirect_to order_beauty_path(:id=>@order_beauty.id)
      end
    end
  end
  


  def show
    @title = "美容工单/明细"
    @buttons.push :action => order_beauties_path, :label => "返回"
  	@order_beauty = OrderBeauty.find params[:id]
    if params.has_key? :save
      if @order_beauty.order_beauty_items.blank?
        @infos.push "请增加美容项目"
      else
        @order_beauty.update_receive_status
      end
    elsif params.has_key? :check
      @order_beauty.update(status: 4)
    end
    if params.has_key? :payment 
      @order_beauty.update(payment_method: params[:payment_method], payment_status: 1, pay_datetime: Time.now, pay_total: params[:pay_total])
    end
  end

  def destroy
    @order_beauty = OrderBeauty.find params[:id]
    @order_beauty.destroy
    redirect_to order_beauties_path
  end


  private
  def set_menu
    @mainmenu = :order
  end
end
